package com.ling.sdk.ui

import android.content.Intent
import android.content.IntentFilter
import android.content.res.Configuration
import android.graphics.Color
import android.os.Bundle
import android.support.annotation.CallSuper
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.LinearLayout.VERTICAL
import com.alibaba.android.arouter.launcher.ARouter
import com.ling.sdk.app.ActivityStack
import com.ling.sdk.live.ILiveUI
import com.ling.sdk.live.ILiveUIParent
import com.ling.sdk.live.LiveManager
import com.ling.sdk.utils.NetworkStateReceiver
import me.jessyan.autosize.AutoSize
import me.jessyan.autosize.AutoSizeConfig
import me.yokeyword.fragmentation.SupportActivity

abstract class BaseActivity : SupportActivity(), ILiveUIParent, ILiveUI, IInit {

    var titleView: ITitle? = null
        set(value) { //当它被赋值的时候才去更新
            field = value; setUpTitleView()
        }
    var stateView: IStateView? = null
        set(value) {
            field = value;setUpStateView()
        }
    lateinit var contentRootView: View

    private val titleViewParent = lazy { LinearLayout(this).apply { orientation = VERTICAL; setBackgroundColor(Color.WHITE) } }

    private val stateViewParent = lazy { FrameLayout(this) }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)

        val id = getLayoutId()
        if (id != -1) setContentView(id)


        this.networkStateReceiver = NetworkStateReceiver()//监听网络变化
        this.networkStateReceiver?.token = ActivityStack.genKey(this)
        registerReceiver(networkStateReceiver, IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"))
    }

    abstract fun getLayoutId(): Int


    override fun onInitView() {}
    override fun onInitData() {}
    override fun onInitListener() {}
    override fun onInitTitleState() {}

    override fun onResume() {
        AutoSize.autoConvertDensityOfGlobal(this)
        super.onResume()
    }


    override fun onConfigurationChanged(newConfig: Configuration?) {
        super.onConfigurationChanged(newConfig)
        AutoSize.autoConvertDensityOfGlobal(this)
    }


    //网络状态的监听
    private var networkStateReceiver: NetworkStateReceiver? = null



    override fun setContentView(layoutResID: Int) {
        setContentView(layoutInflater.inflate(layoutResID, null, false))
    }

    override fun setContentView(view: View) {
        setContentView(view, view.layoutParams)
    }

    override fun setContentView(view: View, params: ViewGroup.LayoutParams?) {

        contentRootView = view

        if (params != null)
            super.setContentView(contentRootView, params)
        else
            super.setContentView(contentRootView)

        setContentViewAfter()

        onInitTitleState()

        onInitView()
        onInitListener()
        onInitData()

        add(this)
    }

    open fun setContentViewAfter() {}


    //动态装载TitleView
    private fun setUpTitleView() {
        titleView?.getView()?.addToParent(titleViewParent.value, 0, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
        contentRootView.addToParent(titleViewParent.value)

        if (titleViewParent.value.parent == null)
            super.setContentView(titleViewParent.value)
    }

    private fun setUpStateView() {

        if (!stateViewParent.isInitialized()) {
            //如果状态父布局没有被初始化

            contentRootView.addToParent(stateViewParent.value)

            if (titleViewParent.isInitialized()) {
                stateViewParent.value.addToParent(titleViewParent.value)
            } else {
                super.setContentView(stateViewParent.value)
            }
        }

        stateView?.getLoadingView()?.addToParent(stateViewParent.value)
        stateView?.getEmptyView()?.addToParent(stateViewParent.value)
    }

    private fun View.addToParent(viewGroup: ViewGroup?, index: Int = -1, params: ViewGroup.LayoutParams? = ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)) {
        viewGroup?.also {
            if (this.parent != it) {
                (this.parent as? ViewGroup)?.removeView(this)
                if (index == -1) it.addView(this, params)
                else it.addView(this, index, params)
            }
        }
    }

    fun getRootView() = if (contentRootView is ViewGroup) contentRootView as ViewGroup else contentRootView.parent as ViewGroup


    @CallSuper
    override fun onDestroy() {
        networkStateReceiver?.let { unregisterReceiver(networkStateReceiver) }
        super.onDestroy()
    }

    override fun finish() {
        super.finish()
        LiveManager.onActivityFinish(this)
    }

    override fun finishActivity(requestCode: Int) {
        super.finishActivity(requestCode)
        LiveManager.onActivityFinish(this)
    }

    override fun add(live: ILiveUI?) {
        LiveManager.addLiveUI(this, live)
    }

    override fun remove(live: ILiveUI?) {
        LiveManager.removeLiveUI(this, live)
    }

    override fun handler() = LiveManager.handler(this)

    override fun sendMessage(data: Any) {
        LiveManager.sendMessage(this, this, data)
    }

    override fun sendMessageAsync(data: Any) {
        LiveManager.sendMessageAsync(this, this, data)
    }

    override fun onUIActivityOnResult(requestCode: Int, result: Int, data: Intent?) {}

    override fun onCleanUp() {}

    override fun onActivityFinish() {}

    override fun onActivityPause() {}

    override fun onActivityResume() {}

    override fun onActivityStop() {}

    override fun getContext() = this

    override fun onNetworkChange(isConnected: Boolean, netType: Int) {}

    override fun receiverMessage(any: Any) = false
}